package eclipse.weibo.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;

import weibo4j.util.DebugPrn;

public class ReadImageUtil {
    private static DebugPrn dp = new DebugPrn(ReadImageUtil.class.getName());
    private static Map<String, ReadImage> map = new HashMap<String, ReadImage>();

    public static ImageData read(URL url) {
        try {
            if (map.containsKey(url.toString())) {
                return (map.get(url.toString())).getData();
            }
            ImageData id = readImg(url);
            ReadImage ri = new ReadImage();
            ri.setData(id);
            ri.setLastAccTime(System.currentTimeMillis());
            map.put(url.toString(), ri);
            return id;
        } catch (Exception ex) {
            dp.error(ex, ex);
        }
        return null;
    }

    public static ImageData read(String url) {
        URL uRl = null;
        try {
            uRl = new URL(url);
        } catch (MalformedURLException ex) {
            dp.error(ex, ex);
        }
        return read(uRl);
    }

    public static void readImgAndDisplay(URL url, Display display, Label label, Composite parent) {
        TThread t = new TThread(url, display, label, parent);
        t.start();
    }

    private static ImageData readImg(URL url) {
        try {
            ImageLoader il = new ImageLoader();
            ImageData[] ids = il.load(url.openStream());
            return ids[0];
        } catch (Exception ex) {
            dp.error(ex, ex);
        }

        return null;
    }

    static class TThread extends Thread {
        private Display display;
        private Label label;
        private Composite parent;
        private URL url;
        private ImageData id = null;

        public TThread(URL url, Display display, Label label, Composite parent) {
            this.url = url;
            this.display = display;
            this.label = label;
            this.parent = parent;
        }

        public void run() {
            this.id = ReadImageUtil.read(url);
            if (this.id != null) {
                this.display.asyncExec(new Runnable() {
                    public void run() {
                        label.setImage(new Image(ReadImageUtil.TThread.this.parent.getDisplay(), ReadImageUtil.TThread.this.id));
                    }
                });
            }
        }
    }
}